package com.satan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.satan.entity.SysRoleMenu;
import com.satan.entity.response.ResCode;
import com.satan.entity.response.ResultEntity;
import com.satan.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SysRoleMenuController
 * @Description TODO
 * @date 2023/11/26 0:02
 * @Version 1.0
 */
@RestController
@RequestMapping("/role/menu")
public class SysRoleMenuController {
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public ResultEntity menus(@PathVariable(value = "id")Integer id){
        List<SysRoleMenu> roleMenuList = sysRoleMenuService.list(new
                QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIdList = roleMenuList.stream().map(p ->
                p.getMenuId()).collect(Collectors.toList());
        return ResultEntity.success(menuIdList);
    }
    /**
     * 更新角色权限信息
     * @param id
     * @param menuIds
     * @return
     */
    @Transactional
    @PostMapping("/update/{id}")
    @PreAuthorize("hasAuthority('system:role:menu')")
    public ResultEntity updateMenus(@PathVariable(value = "id")Long id, @RequestBody Long[]
            menuIds){
        boolean b=sysRoleMenuService.updateMenus(id, menuIds);
        if(b){
            return ResultEntity.success(null);
        }else{
            return ResultEntity.fail(ResCode.UPDATE_ERROR);
        }

    }
}
